package com.renwei.yunlong.fragment;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.YunLongApplication;
import com.renwei.yunlong.activity.work.GuideListActivity;
import com.renwei.yunlong.activity.work.SendWorkActivity;
import com.renwei.yunlong.activity.work.WorkSearchActivity;
import com.renwei.yunlong.adapter.CompanySelectAdapter;
import com.renwei.yunlong.adapter.ProjectChooseAdapter;
import com.renwei.yunlong.adapter.SwitchCompanyAdapter;
import com.renwei.yunlong.adapter.TabNumberAdapter;
import com.renwei.yunlong.adapter.TablayoutAdapter;
import com.renwei.yunlong.base.BaseLazyFragment;
import com.renwei.yunlong.bean.CompanySelectBean;
import com.renwei.yunlong.bean.LoginBean;
import com.renwei.yunlong.bean.ScreenBean;
import com.renwei.yunlong.bean.ServiceLoginBean;
import com.renwei.yunlong.bean.SwitchCompanyBean;
import com.renwei.yunlong.bean.UpcomingBean;
import com.renwei.yunlong.bean.WorkNumberBean;
import com.renwei.yunlong.event.MainRefreshEvent;
import com.renwei.yunlong.event.SendWorkEvent;
import com.renwei.yunlong.event.WorkNumberEvent;
import com.renwei.yunlong.event.WorkPageScreenEvent;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.DateTimeUtils;
import com.renwei.yunlong.utils.DialogUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.zyf.fwms.commonlibrary.base.baseadapter.BaseRecyclerViewAdapter;
import com.zyf.fwms.commonlibrary.utils.SharedPreUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import io.github.xudaojie.qrcodelib.zxing.DensityUtils;

/**
 * Created by wangqi on 2018/1/5.
 */

public class NewWorkFragment extends BaseLazyFragment implements RadioGroup.OnCheckedChangeListener, View.OnClickListener, HttpTaskListener, TimePickerView.OnTimeSelectListener {
    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.iv_edit)
    ImageView ivEdit;
    @Bind(R.id.iv_cont)
    ImageView ivCont;
    @Bind(R.id.rb_quanbu)
    RadioButton rbQuanbu;
    @Bind(R.id.rb_daiban)
    RadioButton rbDaiban;
    @Bind(R.id.rb_jingban)
    RadioButton rbJingban;
    @Bind(R.id.rg_work)
    RadioGroup rgWork;
    @Bind(R.id.tab_layout)
    TabLayout tabLayout;
    @Bind(R.id.viewpager)
    ViewPager viewpager;
    @Bind(R.id.iv_add)
    ImageView ivAdd;
    @Bind(R.id.view_root)
    CoordinatorLayout viewRoot;
    private static final String TYPE_ALL = "0";
    private static final String TYPE_DAIBAN = "1";
    private static final String TYPE_JINGBAN = "2";

    private String[] titles = {"全部", "工单", "问题", "投诉", "备件"};
    private PopupWindow titlePopWindow;
    private PopupWindow filterPopWindow;
    private PopupWindow chooseWindow;
    private TabNumberAdapter adapter;
    private TextView tvTimeEnd;
    private TextView tvTimeStart;
    private TextView tvProject;
    private TextView tvCompany;
    private TextView tvSort;
    // 筛选 参数
    private String companyCode = "";
    private String contractId = "";
    private String startDate = "";
    private String endDate = "";
    private int mSort = 0;
    private TimePickerView pvTime;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_new_work;
    }

    @Override
    public void onLazyLoad() {
        EventBus.getDefault().register(this);
        initView();
        initTitlePopup();
    }

    private void initView() {
        ivBack.setImageResource(R.mipmap.guide);
        ivCont.setImageResource(R.mipmap.icon_work_search);
        ivEdit.setImageResource(R.mipmap.icon_screen);
        if ("1".equals(companyType)) {
            tvTitle.setText(ownerBean.getRows().getCompany().getCompanyName());
        } else if ("2".equals(companyType)) {
            tvTitle.setText(serviceLoginBean.getRows().getCompany().getCompanyName());
        }
        Drawable titleLeft = getContext().getResources().getDrawable(R.mipmap.tri);
        titleLeft.setBounds(0, 0, titleLeft.getMinimumWidth(), titleLeft.getMinimumHeight());
        tvTitle.setCompoundDrawables(null, null, titleLeft, null);
        tvTitle.setCompoundDrawablePadding(10);

        ivBack.setOnClickListener(this);
        ivCont.setOnClickListener(this);
        ivEdit.setOnClickListener(this);
        tvTitle.setOnClickListener(this);
        ivAdd.setOnClickListener(this);

        rgWork.setOnCheckedChangeListener(this);
        if ("1".equals(companyType)) {
            if (AppHelper.isAdminOrServerDesk(ownerBean)) {
                rbQuanbu.setVisibility(View.VISIBLE);
                rbQuanbu.toggle();
            } else {
                rbQuanbu.setVisibility(View.GONE);
                rbDaiban.setBackgroundResource(R.drawable.selector_rg_bule_left);
                rbDaiban.toggle();
            }
        } else {
            if (AppHelper.isAdminOrServerDesk(serviceLoginBean)) {
                rbQuanbu.setVisibility(View.VISIBLE);
                rbQuanbu.toggle();
            } else {
                rbQuanbu.setVisibility(View.GONE);
                rbDaiban.setBackgroundResource(R.drawable.selector_rg_bule_left);
                rbDaiban.toggle();
            }
        }
    }

    private void initTitlePopup() {
        if (titlePopWindow == null) {
            final View view = LayoutInflater.from(getContext()).inflate(R.layout.pop_swich_title, viewRoot, false);
            titlePopWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            titlePopWindow.setFocusable(true);
            titlePopWindow.setAnimationStyle(R.style.pop_animation_top);
            titlePopWindow.setOutsideTouchable(true);
            titlePopWindow.setBackgroundDrawable(new ColorDrawable(0000000000));
            view.findViewById(R.id.hint_view).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    titlePopWindow.dismiss();
                }
            });
            titlePopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    Drawable titleLeft = getContext().getResources().getDrawable(R.mipmap.up);
                    titleLeft.setBounds(0, 0, titleLeft.getMinimumWidth(), titleLeft.getMinimumHeight());
                    tvTitle.setCompoundDrawables(null, null, titleLeft, null);
                    tvTitle.setCompoundDrawablePadding(10);
                }
            });
        }
    }

    private void getOtherCompany() {
        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            map.put("ownerCode", ownerBean.getRows().getOwnerCode());
            map.put("currentUserId", ownerBean.getRows().getEmployeeId());
        } else if ("2".equals(companyType)) {
            map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
            map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
        }
        ServiceRequestManager.getManager().getOtherCompany(getContext(), JsonMapUtil.mapToJson(map), this);
    }

    private void showTitlePop(List<SwitchCompanyBean.RowsBean> rows) {
        if (rows == null || rows.size() == 0) {
            rows = new ArrayList<>();
        }
        SwitchCompanyBean.RowsBean rowBean = new SwitchCompanyBean.RowsBean();
        rowBean.setCompanyName(tvTitle.getText().toString().trim());
        rows.add(0, rowBean);

        final View view = titlePopWindow.getContentView();
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        final SwitchCompanyAdapter adapter = new SwitchCompanyAdapter(getContext(), tvTitle.getText().toString());
        adapter.setData(rows);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickLitener(new BaseRecyclerViewAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                SwitchCompanyBean.RowsBean bean = adapter.getData().get(position);
                if (!bean.getCompanyName().equals(tvTitle.getText().toString())) {
                    updateCompany(bean);
                } else {
                    titlePopWindow.dismiss();
                }
            }
        });
        titlePopWindow.showAsDropDown(tvTitle);
        Drawable titleLeft = getContext().getResources().getDrawable(R.mipmap.tri);
        titleLeft.setBounds(0, 0, titleLeft.getMinimumWidth(), titleLeft.getMinimumHeight());
        tvTitle.setCompoundDrawables(null, null, titleLeft, null);
        tvTitle.setCompoundDrawablePadding(10);
    }

    //筛选弹框pop
    private void showFilterWindow(View view) {
        if (filterPopWindow == null) {
            View contentView = LayoutInflater.from(getContext()).inflate(R.layout.popu_filter, null);
            filterPopWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            filterPopWindow.setTouchable(true);
            ColorDrawable dw = new ColorDrawable(0xb0808080);
            filterPopWindow.setBackgroundDrawable(dw);
            filterPopWindow.setAnimationStyle(R.style.pop_animation_right);
            filterPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    DialogUtils.backgroundAlpha(getActivity(), 1f);
                }
            });
            initPopWindow(contentView);
        }
        filterPopWindow.showAtLocation(view, Gravity.END, 0, 0);
        DialogUtils.backgroundAlpha(getActivity(), 0.5f);//0.0-1.0
    }

    private void initPopWindow(View contentView) {
        tvTimeEnd = contentView.findViewById(R.id.tv_time_end);
        tvTimeStart = contentView.findViewById(R.id.tv_time_start);
        tvProject = contentView.findViewById(R.id.tv_project);
        tvCompany = contentView.findViewById(R.id.tv_company);
        tvSort = contentView.findViewById(R.id.tv_sort);
        TextView tvType = contentView.findViewById(R.id.tv_type);
        LinearLayout llProject = contentView.findViewById(R.id.ll_project);
        if ("1".equals(companyType)) {
            tvType.setText("服务商");
            llProject.setVisibility(View.GONE);
        } else {
            tvType.setText("业主");
            llProject.setVisibility(View.VISIBLE);
        }
        contentView.findViewById(R.id.rl_select_sort).setOnClickListener(this);
        contentView.findViewById(R.id.rl_select_owner).setOnClickListener(this);
        contentView.findViewById(R.id.rl_select_project).setOnClickListener(this);
        contentView.findViewById(R.id.bt_reset).setOnClickListener(this);
        contentView.findViewById(R.id.bt_confirm).setOnClickListener(this);
        tvTimeStart.setOnClickListener(this);
        tvTimeEnd.setOnClickListener(this);
    }

    private void updateCompany(SwitchCompanyBean.RowsBean bean) {
        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            map.put("userName", ownerBean.getRows().getUserName());
            String ownerPwd = SharedPreUtil.getString(getActivity(), "owner_pwd", "");
            map.put("password", ownerPwd);
        } else if ("2".equals(companyType)) {
            map.put("userName", serviceLoginBean.getRows().getUserName());
            String servPwd = SharedPreUtil.getString(getActivity(), "service_pwd", "");
            map.put("password", servPwd);
        }
        map.put("companyCode", bean.getCompanyCode());
        map.put("phoneFlag", "0");
        map.put("deviceToken", YunLongApplication.getDeviceToken());
        ServiceRequestManager.getManager().updateCompany(getContext(), JsonMapUtil.mapToJson(map), this);
    }

    /**
     * 筛选-企业
     */
    private void companyChoose() {
        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            map.put("exeType", "1");
            map.put("ownerCode", ownerBean.getRows().getOwnerCode());
            map.put("currentUserId", ownerBean.getRows().getEmployeeId());
            map.put("serverName", "");
        } else if ("2".equals(companyType)) {
            map.put("useFlag", "1");
            map.put("type", "1");
            map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
            map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
            map.put("serverName", "");
        }
        ServiceRequestManager.getManager().getCompanyChoose(getActivity(), JsonMapUtil.mapToJson(map), this);
    }

    //popupWindow弹框
    private void showPopuSelector(final View view, View contentView) {
        chooseWindow = new PopupWindow(contentView, DensityUtils.dp2px(getContext(), 300), ViewGroup.LayoutParams.MATCH_PARENT, true);
        chooseWindow.setTouchable(true);
        ColorDrawable dw = new ColorDrawable(0xb0808080);
        chooseWindow.setBackgroundDrawable(dw);
        chooseWindow.setAnimationStyle(R.style.pop_animation_right);

        chooseWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                filterPopWindow.showAtLocation(view, Gravity.RIGHT, 0, 0);
            }
        });
        filterPopWindow.dismiss();
        DialogUtils.backgroundAlpha(getActivity(), 0.5f);//0.0-1.0
        chooseWindow.showAtLocation(view, Gravity.RIGHT, 0, 0);
    }

    /**
     * 项目筛选
     */
    private void projectChoose() {
        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            map.put("currentUserId", ownerBean.getRows().getEmployeeId());
            map.put("ownerCode", ownerBean.getRows().getOwnerCode());
            map.put("serviceProviderCode", companyCode);
        } else if ("2".equals(companyType)) {
            map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
            map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
            map.put("ownerCode", companyCode);
        }
        ServiceRequestManager.getManager().getProjectChoose(getActivity(), JsonMapUtil.mapToJson(map), this);
    }

    /**
     * 显示 时间选择器
     *
     * @param view
     */
    private void showPickerView(Date date, View view) {
        Calendar calendar = Calendar.getInstance();
        if (date != null) {
            calendar.setTime(date);
        }
        if (pvTime == null) {
            pvTime = new TimePickerView.Builder(getActivity(), this)
                    //年月日时分秒 的显示与否，不设置则默认全部显示
                    .setType(new boolean[]{true, true, true, false, false, false})
                    .setLabel("", "", "", "", "", "")
                    .isCenterLabel(false)
                    .isDialog(true)
                    .setTitleText("选择日期")
                    .setDate(calendar)
                    .setDividerColor(Color.BLACK)
                    .setTextColorCenter(getResources().getColor(R.color.text_dark_black_color)) //设置选中项文字颜色
                    .setTextColorOut(getResources().getColor(R.color.color_666666))
                    .setDividerColor(getResources().getColor(R.color.color_999999))
                    .setCancelText("取消")
                    .setCancelColor(getResources().getColor(R.color.color_999999))
                    .setSubmitText("确定")
                    .setSubmitColor(getResources().getColor(R.color.blue_color))
                    .setContentSize(20)
                    .setTitleSize(17)
                    .build();
        }
        pvTime.show(view);
    }


    /**
     * 分类选择
     */
    private void sortChoose() {
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popu_selector_layout, null);
        RecyclerView lvPop = contentView.findViewById(R.id.rv_pop);
        TextView tvTitle = contentView.findViewById(R.id.tv_title);
        tvTitle.setText("选择分类");
        contentView.findViewById(R.id.rl_back).setOnClickListener(this);
        lvPop.setLayoutManager(new LinearLayoutManager(getActivity()));
        final ProjectChooseAdapter adapter = new ProjectChooseAdapter(getActivity());
        List<ScreenBean.RowsBean> list = new ArrayList<>();
        for (String title : titles) {
            ScreenBean.RowsBean bean = new ScreenBean.RowsBean();
            bean.setContractName(title);
            list.add(bean);
        }
        adapter.setOnItemClickLitener(new BaseRecyclerViewAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                chooseWindow.dismiss();
                tvSort.setText(adapter.getData().get(position).getContractName());
                mSort = position;
            }
        });
        lvPop.setAdapter(adapter);
        adapter.addAll(list);
        showPopuSelector(ivEdit, contentView);
    }

    /**
     * 获取工作数量
     */
    private void getWorkNumber() {
        HashMap<String, String> map = new HashMap<>();
        map.put("kind", "0");
        map.put("startDate", "");
        map.put("endDate", "");
        map.put("contractId", "");
        map.put("content", "");
        map.put("page", "1");
        map.put("rows", 20 + "");
        if ("2".equals(companyType)) {
            map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
            map.put("ownerCode", "");
        } else if ("1".equals(companyType)) {
            map.put("currentUserId", ownerBean.getRows().getEmployeeId());
            map.put("serviceProviderCode", "");
        }
        ServiceRequestManager.getManager().getWorkList(getContext(), "1",
                JsonMapUtil.mapToJson(map), this);
    }


    private void initData(final String type) {
        //页面，数据源
        List<Fragment> list = new ArrayList<>();
        list.add(new DealAllFragment(type));//全部
        list.add(new DealWorkFragment(type));//工单  OK
        list.add(new DealProblemFragment(type));//问题
        list.add(new DealComplaintsFragment(type));//投诉
        list.add(new DealSpareFragment(type));//备件 OK
        //ViewPager的适配器
        if ("1".equals(type)) {
            adapter = new TabNumberAdapter(getChildFragmentManager(), list, titles);
            viewpager.setAdapter(adapter);
            viewpager.setOffscreenPageLimit(4);
            // 获取 待办数量
            getWorkBarNumber();
        } else {
            viewpager.setAdapter(new TablayoutAdapter(getChildFragmentManager(), list, titles));
            viewpager.setOffscreenPageLimit(4);
        }
        //绑定
        tabLayout.setupWithViewPager(viewpager);
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getCustomView() != null) {
                    tab.getCustomView().findViewById(R.id.tv_title).setSelected(true);
                }
                viewpager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        if (filterPopWindow != null) {
            startDate = "查询起始".equals(tvTimeStart.getText().toString()) ? "" : tvTimeStart.getText().toString();
            endDate = "查询截止".equals(tvTimeEnd.getText().toString()) ? "" : tvTimeEnd.getText().toString();
            EventBus.getDefault().post(new WorkPageScreenEvent(startDate, endDate, companyCode,
                    contractId, mSort));
        }

    }

    private void getWorkBarNumber() {
        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            map.put("currentUserId", ownerBean.getRows().getEmployeeId());
        } else {
            map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
        }
        ServiceRequestManager.getManager().getWorkNumber(getContext(), JsonMapUtil.mapToJson(map), this);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            getWorkNumber();
            if (rbDaiban != null && rbDaiban.isChecked()) {
                getWorkBarNumber();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint()) {
            getWorkNumber();
            if (rbDaiban != null && rbDaiban.isChecked()) {
                getWorkBarNumber();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onSendWorkEvent(SendWorkEvent event) {
        if (rbDaiban.isChecked()) {
            initData(TYPE_DAIBAN);
        } else {
            rbDaiban.toggle();
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i) {
            case R.id.rb_quanbu:
                initData(TYPE_ALL);
                break;
            case R.id.rb_daiban:
                initData(TYPE_DAIBAN);
                break;
            case R.id.rb_jingban:
                initData(TYPE_JINGBAN);
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:// 引导
                // TODO 引导
                GuideListActivity.openActivity(getContext());
                break;
            case R.id.iv_cont:// 搜索
                WorkSearchActivity.openActivity(getActivity());
                break;
            case R.id.iv_edit:// 筛选
                showFilterWindow(view);
                break;
            case R.id.iv_add:// 发起工单
                SendWorkActivity.OpenActivity(getActivity(), ivAdd);
                break;
            case R.id.tv_title:
                getOtherCompany();
                break;
            case R.id.rl_back:
                chooseWindow.dismiss();
                filterPopWindow.showAtLocation(ivEdit, Gravity.END, 0, 0);
                break;
            case R.id.rl_select_sort: // pop 分类
                sortChoose();
                break;
            case R.id.rl_select_owner: // pop 公司选择
                companyChoose();
                break;
            case R.id.rl_select_project: // pop 企业选择
                projectChoose();
                break;
            case R.id.bt_reset:
                filterPopWindow.dismiss();
                filterPopWindow = null;
                companyCode = "";
                contractId = "";
                mSort = 0;
                tvTimeStart.setText("查询起始");
                tvTimeEnd.setText("查询截止");
                EventBus.getDefault().post(new WorkPageScreenEvent("", "", "",
                        "", 0));
                break;
            case R.id.bt_confirm:
                startDate = "查询起始".equals(tvTimeStart.getText().toString()) ? "" : tvTimeStart.getText().toString();
                endDate = "查询截止".equals(tvTimeEnd.getText().toString()) ? "" : tvTimeEnd.getText().toString();
                filterPopWindow.dismiss();
                EventBus.getDefault().post(new WorkPageScreenEvent(startDate, endDate, companyCode,
                        contractId, mSort));
                viewpager.setCurrentItem(mSort);
                break;
            case R.id.tv_time_start:
                showPickerView(DateTimeUtils.string2Date(tvTimeStart.getText().toString(), "yyyy-MM-dd"), view);
                break;
            case R.id.tv_time_end:
                showPickerView(DateTimeUtils.string2Date(tvTimeEnd.getText().toString(), "yyyy-MM-dd"), view);
                break;
            default:
                break;
        }
    }

    @Override
    public void onTimeSelect(Date date, View v) {
        switch (v.getId()) {
            case R.id.tv_time_start:
                if ("查询截止".equals(tvTimeEnd.getText().toString())) {
                    tvTimeStart.setText(DateTimeUtils.date2String(date, "yyyy-MM-dd"));
                } else {
                    if (DateTimeUtils.compareTime(tvTimeEnd.getText().toString())
                            < DateTimeUtils.compareTime(DateTimeUtils.date2String(date, "yyyy-MM-dd"))) {
                        showCenterInfoMsg("结束时间不能小于开始时间");
                    } else {
                        tvTimeStart.setText(DateTimeUtils.date2String(date, "yyyy-MM-dd"));
                    }
                }
                break;
            case R.id.tv_time_end:
                if ("查询起始".equals(tvTimeStart.getText().toString())) {
                    tvTimeEnd.setText(DateTimeUtils.date2String(date, "yyyy-MM-dd"));
                } else {
                    if (DateTimeUtils.compareTime(DateTimeUtils.date2String(date, "yyyy-MM-dd")) <
                            DateTimeUtils.compareTime(tvTimeStart.getText().toString())) {
                        showCenterInfoMsg("结束时间不能小于开始时间");
                    } else {
                        tvTimeEnd.setText(DateTimeUtils.date2String(date, "yyyy-MM-dd"));
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1:
                SwitchCompanyBean bean = new Gson().fromJson(result, SwitchCompanyBean.class);
                showTitlePop(bean.getRows());
                break;
            case 2:
                if ("1".equals(companyType)) {
                    LoginBean value = new Gson().fromJson(result, LoginBean.class);
                    if (value.getMessage().getCode() == 200) {

                        // 友盟 推送接口
                        HashMap<String, String> map = new HashMap<>();
                        map.put("deviceToken", YunLongApplication.getDeviceToken());
                        map.put("phoneFlag", "0");
                        map.put("userId", value.getRows().getEmployeeId());
                        map.put("ownerCode", value.getRows().getOwnerCode());
                        ServiceRequestManager.getManager().pushInit(getContext(), JsonMapUtil.mapToJson(map), null);

                        mCache.put("loginBean", value);
                        mCache.put("companyType", "1");
                        EventBus.getDefault().post(new MainRefreshEvent());
                    } else {
                        showCenterInfoMsg(value.getMessage().getMessage());
                    }
                } else if ("2".equals(companyType)) {
                    ServiceLoginBean value = new Gson().fromJson(result, ServiceLoginBean.class);
                    if (value.getMessage().getCode() == 200) {

                        // 友盟 推送接口
                        HashMap<String, String> map = new HashMap<>();
                        map.put("deviceToken", YunLongApplication.getDeviceToken());
                        map.put("phoneFlag", "0");
                        map.put("userId", value.getRows().getEmployeeId());
                        map.put("serviceProviderCode", value.getRows().getServiceProviderCode());
                        ServiceRequestManager.getManager().pushInit(getContext(), JsonMapUtil.mapToJson(map), null);

                        mCache.put("serviceLoginBean", value);
                        mCache.put("companyType", "2");
                        EventBus.getDefault().post(new MainRefreshEvent());
                    } else {
                        showCenterInfoMsg(value.getMessage().getMessage());
                    }
                }
                titlePopWindow.dismiss();
                break;
            case 3: // 获取待办工单 数量
                UpcomingBean upcomingBean = new Gson().fromJson(result, UpcomingBean.class);
                if (upcomingBean.getMessage().getCode() == 200) {
                    EventBus.getDefault().post(new WorkNumberEvent(upcomingBean.getTotal()));
                }
                break;
            case 4://企业筛选
                CompanySelectBean companySelectBean = new Gson().fromJson(result, CompanySelectBean.class);
                if (companySelectBean.getMessage().getCode() == 200) {
                    View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popu_selector_layout, null);
                    RecyclerView lvPop = contentView.findViewById(R.id.rv_pop);
                    TextView tvTitle = contentView.findViewById(R.id.tv_title);
                    if ("1".equals(companyType)) {
                        tvTitle.setText("选择服务商");
                    } else {
                        tvTitle.setText("选择业主");
                    }
                    contentView.findViewById(R.id.rl_back).setOnClickListener(this);
                    lvPop.setLayoutManager(new LinearLayoutManager(getActivity()));
                    List<CompanySelectBean.Rows> rows = companySelectBean.getRows();
                    CompanySelectBean.Rows rowBean = new CompanySelectBean.Rows();
                    rowBean.setServerName("全部");
                    rows.add(0, rowBean);
                    final CompanySelectAdapter adapter = new CompanySelectAdapter(getContext(), companyType);
                    adapter.setPicShow(false);
                    adapter.setOnItemClickLitener(new BaseRecyclerViewAdapter.OnItemClickLitener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            CompanySelectBean.Rows bean = adapter.getItem(position);
                            chooseWindow.dismiss();
                            tvCompany.setText(bean.getServerName());
                            if (TextUtils.isEmpty(bean.getCompanyCode()) || !bean.getCompanyCode().equals(companyCode)) {
                                companyCode = bean.getCompanyCode();
                                contractId = "";
                                tvProject.setText("全部");
                            }
                        }
                    });
                    lvPop.setAdapter(adapter);
                    adapter.setData(rows);
                    showPopuSelector(ivEdit, contentView);
                }
                break;
            case 5: // 项目选择
                ScreenBean screenBean = new Gson().fromJson(result, ScreenBean.class);
                if (screenBean.getMessage().getCode() == 200) {
                    if (screenBean.getRows().size() != 0) {
                        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popu_selector_layout, null);
                        RecyclerView lvPop = contentView.findViewById(R.id.rv_pop);
                        TextView tvTitle = contentView.findViewById(R.id.tv_title);
                        tvTitle.setText("选择项目");
                        contentView.findViewById(R.id.rl_back).setOnClickListener(this);
                        lvPop.setLayoutManager(new LinearLayoutManager(getActivity()));
                        final ProjectChooseAdapter adapter = new ProjectChooseAdapter(getActivity());
                        ScreenBean.RowsBean rowBean = new ScreenBean.RowsBean();
                        rowBean.setContractName("全部");
                        screenBean.getRows().add(0, rowBean);

                        adapter.setOnItemClickLitener(new BaseRecyclerViewAdapter.OnItemClickLitener() {
                            @Override
                            public void onItemClick(View view, int position) {
                                chooseWindow.dismiss();
                                tvProject.setText(adapter.getData().get(position).getContractName());
                                if (adapter.getData().get(position).getContractId() != 0) {
                                    contractId = adapter.getData().get(position).getContractId() + "";
                                } else {
                                    contractId = "";
                                }
                            }
                        });
                        lvPop.setAdapter(adapter);
                        adapter.addAll(screenBean.getRows());
                        showPopuSelector(ivEdit, contentView);
                    } else {
                        showCenterInfoMsg("未查询到项目");
                    }

                } else {
                    showCenterInfoMsg(screenBean.getMessage().getMessage());
                }
                break;
            case 6: //获取数量
                WorkNumberBean workNumberBean = new Gson().fromJson(result, WorkNumberBean.class);
                if (workNumberBean.getMessage().getCode() == 200) {
                    List<Integer> list = new ArrayList<>();
                    WorkNumberBean.RowsBean row = workNumberBean.getRows();
                    list.add(row.getTotalNum());
                    list.add(row.getNowMonthTotalNum());
                    list.add(row.getNowMonthNum());
                    list.add(row.getNowMonthOverNum());
                    list.add(row.getSparNum());

                    for (int i = 0; i < tabLayout.getTabCount(); i++) {
                        final TabLayout.Tab tab = tabLayout.getTabAt(i);
                        if (tab.getCustomView() == null) {
                            tab.setCustomView(adapter.getTabView(getContext(), i, list.get(i)));
                        } else {
                            CommonUtils.setBarTextView((TextView) tab.getCustomView().findViewById(R.id.tv_bar), list.get(i));
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {

    }

}
